
import { useLoginedStore } from '@/stores/logined';

const store = useLoginedStore();

function isMobile() {
  const regexp = /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/;
  // 获得浏览器相关信息(即获得用户代理)
  const ua = navigator.userAgent;
  const mobile = ua.match(regexp);
  // console.log( mobile );
  // 以 boolean 形式返回判断结果
  return Boolean(mobile);
}

const routes = [
  {
    path: '/',
    name: 'home',
    component: () => import('@/views/mobile/Home.vue'),
    // 路由独享守卫
    beforeEnter: (to, from) => {
      // 若非移动设备则去往电脑版首页
      if( !isMobile() ) {
        return '/pc';
      }
      // 检查目标路由是否是 login 或 register
      if( to.name == 'login' || to.name == 'register' ) {
        return true;
      }
      // 若已经登录
      if( store.logined ) {
        return true; // 则直接放行
      }
      return '/' ; // 否则导航到登录页面
    },
    // 定义子路由(即嵌套路由)
    children: [
      {
        path: '',
        name: 'login',
        component: () => import('@/views/mobile/Login.vue'),
        meta: {
          title: '登录'
        },
        // 子路由独享的守卫
        beforeEnter: () => {
          if( store.logined ) { // 若已登录
            return '/main'; // 则导航到主页面(不必再显示登录页面)
          }
        }
      },
      {
        path: 'register',
        name: 'register',
        component: () => import('@/views/mobile/Register.vue'),
        meta: {
          title: '注册'
        }
      },
      {
        path: 'main',
        name: 'main',
        component: () => import('@/views/mobile/Main.vue'),
        meta: {
          title: '主页'
        }
      },
      {
        path: 'user',
        name: 'userManager',
        component: () => import('@/views/mobile/Main.vue'),
        meta: { title: '用户管理' }
      },
      {
        path: 'file-manager',
        name: 'fileManager',
        component: () => import('@/views/mobile/FileManager.vue'),
        meta: { title: '文件管理' }
      },
      {
        path: 'personal',
        name: 'personal',
        component: () => import('@/views/mobile/Pensonal.vue'),
        meta: { title: '个人设置' }
      }
    ]
  },
  {
    path: '/pc',
    component: () => import('@/views/computer/Home.vue'),
    // 路由独享守卫
    beforeEnter: (to, from) => {
      // 若是移动设备则去往移动版首页
      if( isMobile() ) {
        return '/';
      }
    }
  }
];

export default routes;